<template>
  <a-row type="flex" style="flex-flow: inherit;background-color: #fff;height: 100%;">
    <a-col :span="7" style="padding: 20px;border-right: 1px solid #ddd;">
      <h1 class="title" style="text-align: center;margin-bottom: 50px;">预约咨询</h1>
      <a-form-model layout="vertical" :model="form" :rules="rules">
        <a-form-model-item label="咨询人">
          <a-input v-model="form.consultantName" placeholder="" disabled />

        </a-form-model-item>
        <a-form-model-item label="身份证号">
          <a-input v-model="form.identification" placeholder="" disabled />
        </a-form-model-item>
        <a-form-model-item label="人员类型">
          <j-dict-select-tag v-model="form.consultantType" dictCode="personTypeConsult" placeholder="请选择"
            style="min-width: 100px" disabled />

        </a-form-model-item>
        <a-form-model-item label="联系电话">
          <a-input v-model="form.phone" placeholder="" disabled />
        </a-form-model-item>


        <a-form-model-item label="咨询次数">
          <a-input v-model="form.consultNum" placeholder="请输入" disabled />
        </a-form-model-item>
        <a-form-model-item label="咨询主题" prop="consultTopic">
          <a-input v-model="form.consultTopic" placeholder="" />
        </a-form-model-item>
        <a-form-model-item label="谈话方式">
          <a-select v-model="form.consultType" placeholder="请选择">
            <a-select-option value="1">线上咨询</a-select-option>
            <a-select-option value="2">线下咨询</a-select-option>
          </a-select>
        </a-form-model-item>
        <a-form-model-item label="谈话地点" prop="placeConversationId" v-if="form.consultType == 2">
          <a-cascader :options="areaOptions" placeholder="请选择" :load-data="loadCascader" changeOnSelect
            :fieldNames="{ label: 'name', value: 'code', children: 'children' }" change-on-select
            v-model="form.placeConversationId" />
        </a-form-model-item>
        <a-form-model-item label="详细地址" prop="detailAddress" v-if="form.consultType == 2">
          <a-input v-model="form.detailAddress" placeholder="请输入" />
        </a-form-model-item>
        <a-form-model-item label="开始时间">
          <a-date-picker v-model="form.appointStartTime" style="width: 100%;" show-time format="YYYY-MM-DD HH:mm:ss" @change="form.appointEndTime = null"
            value-format="YYYY-MM-DD HH:mm:ss" placeholder="请选择"></a-date-picker>

        </a-form-model-item>
        <a-form-model-item label="结束时间">
          <a-date-picker v-model="form.appointEndTime" :disabledDate="disabledDate" :disabledTime="disabledTime" @change="onCheckPlan"
            style="width: 100%;" show-time format="YYYY-MM-DD HH:mm:ss" value-format="YYYY-MM-DD HH:mm:ss"
            placeholder="请选择"></a-date-picker>
        </a-form-model-item>

        <a-form-model-item>
          <div style="text-align: center;padding-top: 50px;border-top: 1px solid #ddd;">
            <a-button style="margin-right: 20px;width: 140px;" @click="onCancel">
              取消
            </a-button>
            <a-button type="primary" style="margin-right: 20px;width: 140px;" @click="onSubmit">
              确定
            </a-button>
          </div>
        </a-form-model-item>
      </a-form-model>
    </a-col>
    <a-col :span="17" style="padding: 20px;">
      <Schedule class="scheduleBox" ref="scheduleId" />
    </a-col>
  </a-row>
</template>

<script>
  import Schedule from './components/Schedule'
  import moment from 'moment'
  import {
    mapGetters
  } from 'vuex'
  import {
    consultDetail,
    consultApplication,
    consultNum,
    planList,
    checkPlan
  } from '@/api/sjsk/psycholog/consult'
  import {
    getXzqhList,
    getXzqhByCode,
  } from '@/api/api'
  export default {
    components: {
      Schedule
    },
    computed: {
      ...mapGetters(["userInfo"]),
      // disabledDate: function() {
      //   console.log(this.appointStartTime)
      // },

    },
    data() {
      return {
        areaOptions: [],
        form: {
          consultantName: '',
          identification: '',
          consultantType: '',
          phone: '',
          consultNum: '',
          consultTopic: '',
          consultType: '',
          appointStartTime: '',
          appointEndTime: '',
          placeConversationId: [],
          placeConversation: [],
          detailAddress: '',
        },
        rules: {

        }
      }
    },
    created() {
      this.getXzqh()
      this.getDetail()
    },
    async mounted() {
      // this.onQuery()
    },
    methods: {
      
      getXzqh() {
        getXzqhByCode({
          codeList: [460000000000]
        }).then((res) => {
          if (res.success) {
            this.areaOptions = res.result.map(item => {
              item.isLeaf = false
              return item
            })
          }
        })
      },
      loadCascader(selectedOptions) {
        console.log(selectedOptions)
        const placeConversation = selectedOptions.map(item => {
          return item.name
        })
        this.form.placeConversation = placeConversation.toString()
        
        const targetOption = selectedOptions[selectedOptions.length - 1];
        targetOption.loading = true;
        getXzqhList({
          level: targetOption.level + 1,
          parent: targetOption.code
        }).then(async (res) => {
          if (res.success) {
            targetOption.loading = false
            targetOption.children = res.result.map(item => {
              item.isLeaf = false
              return item
            })
            this.areaOptions = [...this.areaOptions];
            console.log(this.areaOptions)
          }
        })
      },
      getPlanList(id) {
        planList(id).then(res => {
          const scheduleData = res.result.map(item => {
            return {
              id: item.id,
              title: item.title,
              start: item.startTime,
              end: item.endTime,
              overdue: item.overdue,
              textColor: '#000',
              className: ["bgColor", "monthBlackColor"]
            }
          })
          this.$refs.scheduleId.setScheduleData(scheduleData, 'timeGridDay')
        })
      },
      onCheckPlan() {
        if(this.form.appointStartTime && this.form.appointEndTime) {
          checkPlan({
            startTime: this.form.appointStartTime,
            endTime: this.form.appointEndTime,
            userId: this.$route.query.personId
          }).then(res => {
            if(res.result) {
              this.$message.error('预约时间与计划时间冲突')
              this.form.appointEndTime = ''
            }
          }) 
        }
      },
      
      getConsultNum(item) {
        const obj = {
          id: '',
          type: ''
        }
        if(item.personId) {
          obj.id = item.personId
          obj.type = 1
        }
        if(item.socialId) {
          obj.id = item.socialId
          obj.type = 2
        }
        consultNum(obj).then(res => {
          this.form.consultNum = res.result
        })
      },
      disabledDate(current) {
        return current.format('YYYY-MM-DD') !== moment(this.form.appointStartTime).format('YYYY-MM-DD')
      },
      disabledTime(current) {
        const startTime = moment(this.form.appointStartTime)
        const range = (start, end) => {
            const result = [];
            for (let i = start; i < end; i++) {
                result.push(i);
            }
            return result;
        }
        const hour = startTime.hours(); // 获取当前的小时
        const min = startTime.minutes(); // 获取当前的分钟
        const second = startTime.seconds(); // 获取当前秒
        
        const curMin = current.minutes();
        const curSecond = current.seconds();
        let dateObj = {
          disabledHours: () => range(0, 24).splice(0, hour),
          disabledMinutes: () => range(0, 60).splice(0, min),
          disabledSeconds: () => range(0, 60).splice(0, second)
        };
        if(current.format('mm') !== startTime.format('mm')) {
          delete dateObj.disabledSeconds
        }
        return dateObj
      },
      getDetail() {
        
        consultDetail({
          id: this.$route.query.id,
          type: this.$route.query.type
        }).then(res => {
          res.result.placeConversationId = res.result.placeConversationId ? res.result.placeConversationId.split(',') : []
          Object.assign(this.form, res.result)
          this.getConsultNum(res.result)
          this.getPlanList(this.$route.query.personId)
        })
      },
      onSubmit() {
        const form = JSON.parse(JSON.stringify(this.form))
        if (this.$route.query.isAgain == 'true') {
          delete form.id
        }
        form.placeConversationId = form.placeConversationId.toString()

        consultApplication(form).then(res => {
          if (res.success) {
            this.$message.success('预约成功')
            setTimeout(() => {
              this.onCancel()
            }, 1500)
          } else {
            this.$message.error(res.message)
          }
        })
      },
      onCancel() {
        this.$router.back()
      },
    }

  }
</script>
<style lang="less" scoped>
  .topBox /deep/.ant-row {
    margin-bottom: 0;
  }

  /deep/.ant-col-7 {
    width: 28%;
  }

  /deep/.ant-col-4 {
    width: 16%;
  }
</style>
